<template>
  <div class="update-photo">
    <img
      :src="image"
      ref='image'
    >
    <van-nav-bar
      class="bottomnav"
      left-text="返回"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="photoConfirm"
    />
  </div>
</template>
<script>
import { updataUserPhoto } from '@/api/user'

import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
  props: ['previewimage'],
  data() {
    return {
      image: URL.createObjectURL(this.previewimage),
      cropper: null
    }
  },
  mounted() {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true

    })
  },
  methods: {
    getCroppedCanvas() {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    },
    async photoConfirm() {
      this.$toast.loading({
        message: '保存中',
        forbidclick: true,
        duration: 0
      })

      const file = await this.getCroppedCanvas()

      const fd = new FormData()
      fd.append('photo', file)
      const res = await updataUserPhoto(fd)

      this.$toast.success('保存成功')
      this.$emit('confirm', res.data.data.photo)
      this.$emit('close')
    }
  }
  // watch: {
  //   previewimage(newVal, oldVal) {
  //     this.image = URL.createObjectURL(newVal)
  //   }
  // }
}
</script>
<style lang="less" scoped>
.update-photo {
  .img {
    display: block;
    max-width: 100%;
  }
  .bottomnav {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #000;
  }
}
</style>